package com.example.easyutils.travel;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.easyutils.BaseActivity;
import com.example.easyutils.Prove;
import com.example.easyutils.R;
import com.example.easyutils.httputil.HttpGetRequest;
import com.example.easyutils.util.MyTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
//景点
public class TravelActivity extends BaseActivity {
    private static final int SUCCESS_CODE=1,ERROR_CODE=2,WARN_CODE=3,PROVINCE_SUCCESS_CODE = 4,PROVINCE_ERROR_CODE = 5,PROVINCE_CITY_SUCEESS = 6;
    private RecyclerView travelRecycleView;
    private LinearLayoutManager mLinearLayoutManager;
    private RecycleViewTravel recycleViewTravel;
    private Map showResult;
    private EditText cityEditext;
    private List list,provinceList,provinIdList,listCity,cityList;
    private Spinner spinne1,spinne2;
    private ArrayAdapter<String> adapter;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS_CODE:
                    Log.d("textView",showResult+"");
                    List travelList = new ArrayList();
                    travelList = (List) showResult.get("record");
                    mLinearLayoutManager = new LinearLayoutManager(TravelActivity.this,RecyclerView.VERTICAL,false);
                    recycleViewTravel = new RecycleViewTravel(TravelActivity.this,travelList);
                    travelRecycleView.setLayoutManager(mLinearLayoutManager);
                    travelRecycleView.setAdapter(recycleViewTravel);
                    break;
                case ERROR_CODE:
                    break;
                case WARN_CODE:
                    break;
                case PROVINCE_SUCCESS_CODE:
                    Log.d("SUCESS",list+"");
                    provinceList = new ArrayList();
                    provinIdList = new ArrayList();

                    for(int i = 0; i < list.size(); i ++){
                        provinceList.add(((Map)list.get(i)).get("name"));
                        provinIdList.add(((Map)list.get(i)).get("id"));
                    }
                    initSpinner(provinceList,spinne1);
                    break;
                case PROVINCE_CITY_SUCEESS:

                    Log.d("cityList",listCity+"");

                    cityList = new ArrayList();
                    for(int i = 0; i < listCity.size(); i ++){
                        cityList.add(((Map)listCity.get(i)).get("name"));
                    }
                    Log.d("cityList11",cityList+"");
                    initSpinner(cityList,spinne2);
                    break;
                case PROVINCE_ERROR_CODE:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.travel_layout);
        cityEditext = (EditText)findViewById(R.id.cityEdit);
        travelRecycleView = (RecyclerView)findViewById(R.id.travelRecycleView);
        getProvince();
//第一步：定义下拉列表内容
        spinne1 = (Spinner) findViewById(R.id.spinner1);
        spinne2 = (Spinner) findViewById(R.id.spinner2);

    }


    //OnItemSelected监听器
    private class  ProvOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
        String spinner;
        public ProvOnItemSelectedListener(String spinner) {
            this.spinner = spinner;
        }

        @Override
        public void onItemSelected(AdapterView<?> adapters, View view, int position, long id) {
            //获取选择的项的值
            // TODO Auto-generated method stub
            Log.d("您选择的城市id是:",position+1+"");
            if(spinner.equals("spinner1")){
                getCity(position+1);
            }else{
                cityEditext.setText(cityList.get(position).toString());
//                getTravelData();

            }

            adapters.setVisibility(View.VISIBLE);
            String sInfo = adapters.getItemAtPosition(position).toString();
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
        }


        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            String sInfo = "什么也没选！";
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
        }
    }

    private void initSpinner(List list,Spinner spinner){
        //第二步：为下拉列表定义一个适配器
        adapter = new ArrayAdapter<String>(TravelActivity.this, android.R.layout.simple_spinner_item, list);

        //第三步：设置下拉列表下拉时的菜单样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //第四步：将适配器添加到下拉列表上
        spinner.setAdapter(adapter);

        //第五步：添加监听器，
        spinne1.setOnItemSelectedListener(new TravelActivity.ProvOnItemSelectedListener("spinner1"));
        spinne2.setOnItemSelectedListener(new TravelActivity.ProvOnItemSelectedListener("spinner2"));

        //将spinnertext添加到OnTouchListener对内容选项触屏事件处理
        spinner.setOnTouchListener(new Spinner.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                // 将mySpinner隐藏
//                v.setVisibility(View.INVISIBLE);
                Log.i("spinner", "Spinner Touch事件被触发!");
                return false;
            }
        });

        //焦点改变事件处理
        spinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
//                v.setVisibility(View.VISIBLE);
                Log.i("spinner", "Spinner F ocusChange事件被触发！");
            }
        });

    }

    private void getProvince(){//获取省份
        HttpGetRequest.sendOkHttpGetRequst("http://guolin.tech/api/china",
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Log.d("RESULT",result);
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<List>(){

                                }.getType(),new MyTypeAdapter()).create();
                        List dataDetail = gson.fromJson(result,new TypeToken<List>(){

                        }.getType());

                        Log.d("Listending",dataDetail+"");
                        list = new ArrayList<>();
                        list = (List) dataDetail;
                        handler.sendEmptyMessage(PROVINCE_SUCCESS_CODE);
                    }
                });
    }

    private void getCity(int position){//获取城市
        HttpGetRequest.sendOkHttpGetRequst("http://guolin.tech/api/china/"+position,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        String result = response.body().string();
                        listCity = new ArrayList();
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<List>(){

                                }.getType(),new MyTypeAdapter()).create();
                        List dataDetail = gson.fromJson(result,new TypeToken<List>(){

                        }.getType());
                        listCity = dataDetail;
                        handler.sendEmptyMessage(PROVINCE_CITY_SUCEESS);
                    }
                });
    }


    public void clickBtn(View view){
//        getTravelData();
    }
    public void getTravelData(){//获取景点
        String param = cityEditext.getText().toString();
        Log.d("param0",param);
        if(param==""){
            Toast.makeText(TravelActivity.this,"请输入内容",Toast.LENGTH_LONG).show();
            return;
        }
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .get()
                .url("http://scenicspot.market.alicloudapi.com/lianzhuo/scenicspot?city="+param)
                .addHeader("Authorization","APPCODE a6134a2107334cc0b7bb2584ba2f9f56")
                .build();

        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(ERROR_CODE);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.d("SUCCESS",result);
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(new TypeToken<Map<String,Map>>(){

                        }.getType(),new MyTypeAdapter()).create();
                Map<String,Map> dataDetail = gson.fromJson(result,new TypeToken<Map<String,Map>>(){

                }.getType());

                Log.d("dataDetail",dataDetail+"");
//                showResult = dataDetail.get("data");
                handler.sendEmptyMessage(SUCCESS_CODE);
            }
        });
//        client.newCall(request).enqueue(callback);
    }
}

//http://guolin.tech/api/china//省份

//http://guolin.tech/api/china/16//城市
